/**
 * Created by tmac on 15/12/12.
 */

//ZTree模板样
var setting = {
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};

/**
 * 页面初始化加载数据
 */
$(function(){
    $("#db a").click(function(){
        var indicatortype = $(this).attr("indtype");
        dealZtreeIndicatorInfo(indicatortype);
    });

    queryIndicatorInfo("db");

    //关闭iframe
    var index = parent.layer.getFrameIndex(window.name); //获取当前窗体索引
    $('.Close').on('click', function(){
        parent.layer.close(index); //执行关闭
    });

    /**
     * 配置 性能 容量
     * 保存
     */

    $('.press_btn1.treeSave').click(function(){
        var type=$(this).parent().parent().parent().get(0).id;
        var treeObj=$.fn.zTree.getZTreeObj(type+"_ztree");
        var nodes=treeObj.getCheckedNodes(true);
        //sysEcho(nodes);
        var checkitems =[];
        $.each(nodes,function(k,v){
            if(v.isParent==false){
                //sysEcho(v);
                var item={};
                item['indicator_id']= v.indicator_id;
                item['pi_id']= v.pi_id;
                item['resource_id']= v.resource_id;
                checkitems.push(item);
            }
        })
        if(checkitems.length>0){
            updateDataDb(JSON.stringify(checkitems),type);
        }else{
            layer.msg('请勾选指标', {time: 2000});
        }
    });
})

/**
 * 校验
 * @param field
 */
function volidateRange(field){
	rangeContral(field);
}
/**
 * 阀值范围控制
 */
function rangeContral(field){
	var element = $(field).parent().parent().parent().next().find("input[id*='_from_']").eq(0);
	if(field.id.indexOf("_to_")>0&&element.length!=0&&$(element).attr("id").indexOf('lower')==-1){
		if(element.length>0&&field.value!=null&&field.value!=''){
			element.val(field.value);
		}
	}
}
    /**
     * 服务保存处理
     */
/**
 * 点击保存 更新监控指标入库
 */
updateDataDb=function(data,type){
    $.ajax2(basePath,{
        url: "updateMonitorData.do",
        type: "post",
        dataType: 'json',
        data: {
            'data':data,
            'type':type,
            'resource_id':resourceId
        },
        success: function (jsons) {
            if (jsons != null) {
                if(jsons.errorMessage==200){

                    /**
                     * 容量 性能 进程 需要进入下一步处理
                     * 设置容量阀值
                     */
                    if(type=="db"){
                        var data = jsons.data.data;
                        if(data==null){
                            layer.msg('保存成功',{time:2000})
                        }else{
                            //主标题
                            var html='<div class="content_detail"> <div class="control-title"> <i class="user_manage content_current"></i><span>告警级别设置--DB</span> </div>';
                            //副标题
                            $.each(jsons.data.title,function(bcode,titlename){
                                html+='<div class="content_condition"> <div class="content_title">'+titlename+'</div>';
                                if(data[bcode]==null){
                                    html+="<div>没有配置默认阀值</div>";
                                }else{
                                    $.each(data[bcode],function(indicator_name,value){
                                        html+=handlerTemplate(value,"db-template")
                                    });
                                }
                                html+='</div>';
                            });
                            html+='</div><br/><br/><br/><br/>';
                            html+='<div class="btn_bottom"> <div class="spanbtn"> <button class="press_btn1 Save"><i class="save top_current"></i>保存</button> <button class="press_btn2 Close"><i class="del top_current"></i>关闭</button> </div> </div>';
                            $("#"+type).html(html);

                            //1 保存按钮
                            $(".Save").click(function(){
                            	
                            	
                            	
                            	
                            	
                                var holdcapac =[];
                                var isSave=true;
                                $.each($(".content_group"),function(){
                                	
                                	var item={};
                                	var thresholdDbid =$(this).attr("id")
                                	item['thresholdDbId']=thresholdDbid;
                                	
                                	
                                	//if($(target).attr("name").indexOf("From")>0)
                                	var waringFrom = Number($($("#"+thresholdDbid+" input[name=waringFrom]")).val());
                                	var waringTo = Number($($("#"+thresholdDbid+" input[name=waringTo]")).val());
                                	
                                	var errorFrom = Number($($("#"+thresholdDbid+" input[name=errorFrom]")).val());
                                	var errorTo = Number($($("#"+thresholdDbid+" input[name=errorTo]")).val());
                                	
                                	var criticalFrom = Number($($("#"+thresholdDbid+" input[name=criticalFrom]")).val());
                                	var criticalTo = Number($($("#"+thresholdDbid+" input[name=criticalTo]")).val());
                                	
                                	$($("#"+thresholdDbid+" input[name=waringFrom]")).attr("style","border-color:;");
                        			$($("#"+thresholdDbid+" input[name=waringTo]")).attr("style","border-color:;");
                        			$($("#"+thresholdDbid+" input[name=errorFrom]")).attr("style","border-color:;");
                        			$($("#"+thresholdDbid+" input[name=errorTo]")).attr("style","border-color:;");
                        			$($("#"+thresholdDbid+" input[name=criticalFrom]")).attr("style","border-color:;");
                        			$($("#"+thresholdDbid+" input[name=criticalTo]")).attr("style","border-color:;");
                        			
                                	if(waringFrom>waringTo){
                                		$($("#"+thresholdDbid+" input[name=waringFrom]")).attr("style","border-color:red;");
                            			$($("#"+thresholdDbid+" input[name=waringTo]")).attr("style","border-color:red;");
                            			layer.msg('请校验阀值范围',{time:2000});
                            			isSave=false;
                            			return false;
                                	}
                                	if(waringTo>errorFrom){
                                		$($("#"+thresholdDbid+" input[name=waringTo]")).attr("style","border-color:red;");
                            			$($("#"+thresholdDbid+" input[name=errorFrom]")).attr("style","border-color:red;");
                            			layer.msg('请校验阀值范围',{time:2000});
                            			isSave=false;
                            			return false;
                                	}
                                	if(errorFrom>errorTo){
                                		$($("#"+thresholdDbid+" input[name=errorFrom]")).attr("style","border-color:red;");
                            			$($("#"+thresholdDbid+" input[name=errorTo]")).attr("style","border-color:red;");
                            			layer.msg('请校验阀值范围',{time:2000});
                            			isSave=false;
                            			return false;
                                	}
                                	if(errorTo>criticalFrom){
                                		$($("#"+thresholdDbid+" input[name=errorTo]")).attr("style","border-color:red;");
                            			$($("#"+thresholdDbid+" input[name=criticalFrom]")).attr("style","border-color:red;");
                            			layer.msg('请校验阀值范围',{time:2000});
                            			isSave=false;
                            			return false;
                                	}
                                	if(criticalFrom>criticalTo){
                                		$($("#"+thresholdDbid+" input[name=criticalFrom]")).attr("style","border-color:red;");
                            			$($("#"+thresholdDbid+" input[name=criticalTo]")).attr("style","border-color:red;");
                            			layer.msg('请校验阀值范围',{time:2000});
                            			isSave=false;
                            			return false;
                                	}
                                	
                                	
                                	
                                	
                                	item['waringFrom']=$("#"+thresholdDbid+" input[name=waringFrom]").val()
                                    if(!checkIndNotNull($("#"+thresholdDbid+" input[name=waringFrom]"))){
                                        layer.msg('阀值不能为空',{time:2000});
                                        isSave=false;
                                        return false;
                                    }
                                    item['waringTo']=$("#"+thresholdDbid+" input[name=waringTo]").val()
                                    if(!checkIndNotNull($("#"+thresholdDbid+" input[name=waringTo]"))){
                                        layer.msg('阀值不能为空',{time:2000});
                                        isSave=false;
                                        return false;
                                    }
                                    item['errorFrom']=$("#"+thresholdDbid+" input[name=errorFrom]").val()
                                    if(!checkIndNotNull($("#"+thresholdDbid+" input[name=errorFrom]"))){
                                        layer.msg('阀值不能为空',{time:2000});
                                        isSave=false;
                                        return false;
                                    }
                                    item['errorTo']=$("#"+thresholdDbid+" input[name=errorTo]").val()
                                    if(!checkIndNotNull($("#"+thresholdDbid+" input[name=errorTo]"))){
                                        layer.msg('阀值不能为空',{time:2000});
                                        return false;
                                    }
                                    item['criticalFrom']=$("#"+thresholdDbid+" input[name=criticalFrom]").val()
                                    if(!checkIndNotNull($("#"+thresholdDbid+" input[name=criticalFrom]"))){
                                        layer.msg('阀值不能为空',{time:2000});
                                        isSave=false;
                                        return false;
                                    }
                                    item['criticalTo']=$("#"+thresholdDbid+" input[name=criticalTo]").val()
                                    if(!checkIndNotNull($("#"+thresholdDbid+" input[name=criticalTo]"))){
                                        layer.msg('阀值不能为空',{time:2000});
                                        isSave=false;
                                        return false;
                                    }
                                    holdcapac.push(item);
                                });
                                //保存阀值数据
                                if(holdcapac.length>0 && isSave){
                                    saveThresHold(JSON.stringify(holdcapac),type);
                                }
                            });
                            //2 关闭按钮
                            //关闭iframe
                            var index = parent.layer.getFrameIndex(window.name); //获取当前窗体索引
                            $('.Close').on('click', function(){
                                parent.layer.close(index); //执行关闭
                            });
                        }
                    }
                }else{
                    layer.msg(jsons.errorMessage,{time:2000})
                }
            }
        }
    });
}
    /**
     * 查询指标
     * @param indicatortype
     */
    queryIndicatorInfo=function(indicatortype){
        /**
         * 从数据库中查询指标支援
         */
        var param = {
            url: "queryResourceIndicator.do",
            type: "post",
            dataType: 'json',
            data: {
                "resource_id":resourceId,
                "type":indicatortype
            },
            success: function (jsons) {
                if (jsons != null) {
                    if(jsons.errorMessage==200){
                        var zNodes=jsons.data.data;
                        //sysEcho(zNodes);
                        var unknow=jsons.data.unknow;
                        if(unknow!=null && unknow!==''){
                            zNodes=zNodes.concat(jsons.data.unknow);
                        }
                        //1 导入树
                        var treeObj =$.fn.zTree.init($("#"+indicatortype+"_ztree"), setting, zNodes);
                        treeObj.expandAll(false);
                        var nodes=treeObj.getCheckedNodes(true);
                        $.each(nodes,function(k,v){
                            treeObj.checkNode(v.getParentNode(), true, false);//第3个参数代表不选中其子节点；如果设为true会选中所有子节点，但实际子节点只是部分被选中
                        })
                    }else{
                        $("#"+indicatortype+"_ztree").html(jsons.errorMessage);
                    }

                }

            }
        };
       $.ajax(param);

    }
/**
 * 保存阀值
 * @param data
 * @param type
 */
saveThresHold=function(data,type){
    $.ajax2(basePath,{
        url: "saveThreshold.do",
        type: "post",
        dataType: 'json',
        data: {
            'data':data,
            'type':type,
        },
        success: function (jsons) {
            if (jsons != null) {
                if(jsons.errorMessage==200){
                    layer.msg('保存成功',{time:2000})
                    location.reload()
                }else{
                    layer.msg(jsons.errorMessage,{time:2000})
                }
            }else{
                layer.msg("结果错误",{time:2000})
            }
        }
    });
}


/**
 * 处理(点击采集按钮)配置 性能 容量
 * @param indicatortype
 */
dealZtreeIndicatorInfo=function(indicatortype){
    $.ajax2(basePath,{
        url: "dealResourceIndicator.do",
        type: "post",
        dataType: 'json',
        data: {
            "resourceId":resourceId,
            "type":indicatortype
        },
        success: function (jsons) {
            if (jsons != null) {
                if(jsons.errorMessage==200){
                    var zNodes=jsons.data.data;
                    //sysEcho(zNodes);
                    var unknow=jsons.data.unknow;
                    if(unknow!=null && unknow!==''){
                        zNodes=zNodes.concat(jsons.data.unknow);
                    }
                    //1 导入树
                    var treeObj =$.fn.zTree.init($("#"+indicatortype+"_ztree"), setting, zNodes);
                    treeObj.expandAll(false);
                }else{
                    //alert(jsons.errorMessage);
                    layer.msg(jsons.errorMessage, {time: 2000});
                }

            }

        }
    });
}

/**
 * 验证指标非空
 */
function checkIndNotNull(target){
    //sysEcho(target);
    $(target).attr("style","border-color: ;");
    $(target).attr("title","");
	if(($(target).val().trim())==""){
        $(target).attr("style","border-color:red;");
        $(target).next().html("*不能为空！");
        return false;
    }else{
        $(target).attr("style","border-color: ;");
        $(target).next().html("*");
        return true;
    }
}

/**
 * 模版处理方法
 * @param data
 * @returns {*}
 */
handlerTemplate=function(data,node){
    //注册一个Handlebars模版，通过id找到某一个模版，获取模版的html框架
    var template = Handlebars.compile($("#"+node).html());
    //注册一个翻译用的Helper，0翻译成男，1翻译成女
    Handlebars.registerHelper("transformat",function(value){
        //sysEcho(value);
        if(value==false){
            return "否";
        }else if(value==true){
            return "是";
        }
    });
    //时间戳转换时间格式
    Handlebars.registerHelper("prettifyDate", function(timestamp) {
        //format("yyyy-MM-dd HH:mm:ss");
        return (new Date(parseInt(timestamp))).toLocaleString().substr(0,17);
    });
    /**
     * 处理select option选择
     */
    window.Handlebars.registerHelper('select', function( value, options ){
        //sysEcho(value);
        var $el = $('<select />').html( options.fn(this) );
        $el.find('[value="' + value + '"]').attr({'selected':'selected'});
        return $el.html();
    });
    /**
     * 处理isping issyslog 勾选
     */
    Handlebars.registerHelper("selectcheckbox", function(value) {
        //sysEcho(value);
        var result="";
        if(value===true){
            result="checked";
        }
        return result
    });
    return template(data);
}



